package cn.gov.pbc.gd.credit.core.service.report.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.liu.jbase.BaseVo;
import com.liu.jbase.PageListVo;
import com.liu.jbase.ResultVo;
import com.liu.jbase.constant.ResCode;
import com.liu.jbase.service.impl.BaseServiceImpl;
import com.liu.tools.DateUtil;
import com.liu.tools.LogUtil;
import com.liu.tools.StrUtil;
import com.liu.tools.conf.ConfigurerEx;

import cn.gov.pbc.gd.credit.api.corp.ICorpApi;
import cn.gov.pbc.gd.credit.api.report.IReportQueryApi;
import cn.gov.pbc.gd.credit.common.constant.CommonConstant;
import cn.gov.pbc.gd.credit.common.model.UserModel;
import cn.gov.pbc.gd.credit.common.service.redis.IRedisService;
import cn.gov.pbc.gd.credit.common.util.UserUtil;
import cn.gov.pbc.gd.credit.core.service.report.IReportQueryService;
import cn.gov.pbc.gd.credit.vo.corp.ResCorpVo;
import cn.gov.pbc.gd.credit.vo.report.query.ReportQueryVo;
import cn.gov.pbc.gd.credit.vo.report.query.ResQueryDetailVo;
import cn.gov.pbc.gd.credit.vo.report.query.ResQueryTotalVo;
import jxl.report.ReportEnginer;

@Service
public class ReportQueryServiceImpl extends BaseServiceImpl<ResQueryTotalVo, ReportQueryVo, IReportQueryApi> implements IReportQueryService{

	public Logger logger = LoggerFactory.getLogger(ReportQueryServiceImpl.class);

	@Autowired
	private IReportQueryApi reportQueryApi;
	
	@Autowired
	private ICorpApi corpApi;
	
	@Autowired
	private IRedisService redisService;
	
	@Override
	public ResultVo<List<ResQueryTotalVo>> queryTotal(ReportQueryVo vo, HttpServletRequest request) {
		
		
	   UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		
		boolean flag = false;
		
		if(StrUtil.isNull(vo.getCorpId())){
			vo.setCorpId(userModel.getCorpId());
		}
		
		ResCorpVo resCorpVo = corpApi.queryById(vo.getCorpId());
		if("-1".equals(resCorpVo.getParentId())){
			vo.setCorpId(null);
		} 
		
		if(userModel.getRoleList().size() > 1){//业务管理员
			flag = true;
		}
		
		if(! flag && UserUtil.checkRoleType(userModel.getRoleList(), CommonConstant.ROLE_OPRTATOR)){//查询员
			vo.setCorpId(null);
			vo.setOperatorId(userModel.getUserId());
		}
		
		List<ResQueryTotalVo> list = reportQueryApi.queryTotal(vo);
		ResultVo<List<ResQueryTotalVo>> resultVo = new ResultVo<>();
		resultVo.setCode(ResCode.SUCCESS);
		resultVo.setData(list);

		return resultVo;
	}
	
	@Override
	public ResultVo<String> exportQueryTotal(ReportQueryVo vo, HttpServletRequest request, HttpServletResponse response) {
		
		ResultVo<String> resultVo = new ResultVo<>();

		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		
		boolean flag = false;
		
		if(StrUtil.isNull(vo.getCorpId())){
			vo.setCorpId(userModel.getCorpId());
		}
		
		ResCorpVo resCorpVo = corpApi.queryById(vo.getCorpId());
		if("-1".equals(resCorpVo.getParentId())){
			vo.setCorpId(null);
		} 
		if(userModel.getRoleList().size() > 1){//业务管理员

			flag = true;
		}
		
		if(! flag && UserUtil.checkRoleType(userModel.getRoleList(), CommonConstant.ROLE_OPRTATOR)){//查询员
			vo.setCorpId(null);
			vo.setOperatorId(userModel.getUserId());
		}
		
		List<ResQueryTotalVo> list = reportQueryApi.queryTotal(vo);
		
		if(list == null){
			
			logger.error(LogUtil.msg("ReportQueryServiceImpl:exportQueryTotal", vo.getSid(), "数据不存在，req=" + JSON.toJSONString(vo), vo.getIp()));
			resultVo.setCode(ResCode.DATA_NOT_EXSIT);
			return resultVo;
		}
		
		Map<String, Object> map = new HashMap<>();
	    		
		map.put("curTime", DateUtil.format(new Date(), DateUtil.FORMAT_DATE));
		
		if(vo.getBeginTime() == null){
			map.put("beginTime", "2017-06-15");
		} else {
			map.put("beginTime", DateUtil.format(vo.getBeginTime(), DateUtil.FORMAT_DATE));	
		}
		if(vo.getEndTime() == null){
			map.put("endTime", DateUtil.format(new Date(), DateUtil.FORMAT_DATE));
		} else {
			map.put("endTime", DateUtil.format(vo.getEndTime(), DateUtil.FORMAT_DATE));	
		}
		
		map.put("totalList", list);

		String excelPath = ConfigurerEx.getProperty("report.query.total.template");
		
		//String saveFile = ConfigurerEx.getProperty("hyhd.excel.save.path"); 
		
		ReportEnginer enginer = new ReportEnginer();
		
		//String destFile = saveFile + "payfee_" + resOrderVo.getSerialNo() + ".xls";
		InputStream in = null;
		try {
			
			String fileName = "query_" + DateUtil.getCurrentFormatMill() + ".xls";
			
			String mimeType=  "application/octet-stream; charset=UTF-8";
			response.setCharacterEncoding("UTF-8");  
	        response.setContentType(mimeType);
			
	        response.setContentType(mimeType);
	        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + fileName +"\""));
			
			OutputStream out = response.getOutputStream();	
			in = new FileInputStream(excelPath);
			enginer.excute(in, map, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		resultVo.setCode(ResCode.SUCCESS);
		if(in != null){
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultVo;
	}

	@Override
	public ResultVo<List<ResQueryDetailVo>> exportList(ReportQueryVo vo, HttpServletRequest request, HttpServletResponse response) {
		
		ResultVo<List<ResQueryDetailVo>> resultVo = new ResultVo<>();

		UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		
		boolean flag = false;
		
		if(StrUtil.isNull(vo.getCorpId())){
			vo.setCorpId(userModel.getCorpId());
		}
		
		ResCorpVo resCorpVo = corpApi.queryById(vo.getCorpId());
		if("-1".equals(resCorpVo.getParentId())){
			vo.setCorpId(null);
		} 
		if(userModel.getRoleList().size() > 1){//业务管理员

			flag = true;
		}
		
		if(! flag && UserUtil.checkRoleType(userModel.getRoleList(), CommonConstant.ROLE_OPRTATOR)){//查询员
			vo.setCorpId(null);
			vo.setOperatorId(userModel.getUserId());
		}
		
		List<ResQueryDetailVo> list = reportQueryApi.queryList(vo);
		
		if(list == null){
			
			logger.error(LogUtil.msg("ReportQueryServiceImpl:exportList", vo.getSid(), "数据不存在，req=" + JSON.toJSONString(vo), vo.getIp()));
			resultVo.setCode(ResCode.DATA_NOT_EXSIT);
			return resultVo;
		}
		
		Map<String, Object> map = new HashMap<>();
	    		
		map.put("curTime", DateUtil.format(new Date(), DateUtil.FORMAT_DATE));
		if(vo.getBeginTime() == null){
			map.put("beginTime", "2017-06-15");
		} else {
			map.put("beginTime", DateUtil.format(vo.getBeginTime(), DateUtil.FORMAT_DATE));	
		}
		if(vo.getEndTime() == null){
			map.put("endTime", DateUtil.format(new Date(), DateUtil.FORMAT_DATE));
		} else {
			map.put("endTime", DateUtil.format(vo.getEndTime(), DateUtil.FORMAT_DATE));	
		}
		
		map.put("totalList", list);

		String excelPath = ConfigurerEx.getProperty("report.query.list.template");
		
		//String saveFile = ConfigurerEx.getProperty("hyhd.excel.save.path"); 
		
		ReportEnginer enginer = new ReportEnginer();
		
		//String destFile = saveFile + "payfee_" + resOrderVo.getSerialNo() + ".xls";
		InputStream in = null;
		try {
			
			String fileName = "list_" + DateUtil.getCurrentFormatMill() + ".xls";
			
			String mimeType=  "application/octet-stream; charset=UTF-8";
			response.setCharacterEncoding("UTF-8");  
	        response.setContentType(mimeType);
			
	        response.setContentType(mimeType);
	        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + fileName +"\""));
			
			OutputStream out = response.getOutputStream();	
			in = new FileInputStream(excelPath);
			enginer.excute(in, map, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		resultVo.setCode(ResCode.SUCCESS);
		if(in != null){
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultVo;
	}

	@Override
	public ResultVo<PageListVo<ResQueryDetailVo>> pageList(ReportQueryVo vo, HttpServletRequest request) {

		ResultVo<PageListVo<ResQueryDetailVo>> res = new ResultVo<>();
		PageListVo<ResQueryDetailVo> page = new PageListVo<>();
		
        UserModel userModel = UserUtil.getUserModel(vo.getSid(), redisService);
		
		boolean flag = false;
		
		if(StrUtil.isNull(vo.getCorpId())){
			vo.setCorpId(userModel.getCorpId());
		}
		
		ResCorpVo resCorpVo = corpApi.queryById(vo.getCorpId());
		if("-1".equals(resCorpVo.getParentId())){
			vo.setCorpId(null);
		} 
		if(userModel.getRoleList().size() > 1){//业务管理员

			flag = true;
		}
		
		if(! flag && UserUtil.checkRoleType(userModel.getRoleList(), CommonConstant.ROLE_OPRTATOR)){//查询员
			vo.setCorpId(null);
			vo.setOperatorId(userModel.getUserId());
		}
		
		try {
			
			if(vo != null){
				BaseVo baseVo = (BaseVo) vo;
				if(baseVo.getCurPage() != null){
					page.setCurrPage(baseVo.getCurPage());
				}
				if(baseVo.getPageSize() != null){
					page.setPageSize(baseVo.getPageSize());
				}
			}

			PageListVo<ResQueryDetailVo> pageListVo = reportQueryApi.pageList(vo, page);
			res.setCode(ResCode.SUCCESS);
			res.setData(pageListVo);
			
		} catch (Exception e) {
			res.setCode(ResCode.EXCEPTION);
			logger.error(LogUtil.msg("ReportQueryServiceImpl:pageList", "分页查询异常"), e);
		}
		
		return res;
	}
	

}
